import React, { useState, useRef, useEffect } from 'react';
import { Button, Input, Avatar, message, Tooltip, Popconfirm } from 'antd';
import { 
  SendOutlined, 
  SoundOutlined, 
  StopOutlined, 
  ArrowLeftOutlined,
  MessageOutlined,
  MutedOutlined,
  UserOutlined,
  CopyOutlined,
  CheckOutlined,
  LoadingOutlined
} from '@ant-design/icons';
import SpeechRecognition, { useSpeechRecognition } from 'react-speech-recognition';
import { Character, Message } from '../types';
import characterService from '../services/characterService';

const { TextArea } = Input;

interface ConversationPanelProps {
  character: Character;
  onBack: () => void;
}

// 格式化时间戳为时间显示
const formatTime = (timestamp: number): string => {
  const date = new Date(timestamp);
  const hours = date.getHours().toString().padStart(2, '0');
  const minutes = date.getMinutes().toString().padStart(2, '0');
  return `${hours}:${minutes}`;
};

const ConversationPanel: React.FC<ConversationPanelProps> = ({ character, onBack }) => {
  const [messages, setMessages] = useState<Message[]>([]);
  const [inputText, setInputText] = useState<string>('');
  const [isVoiceOutputActive, setIsVoiceOutputActive] = useState<boolean>(true);
  const [isTyping, setIsTyping] = useState<boolean>(false);
  const messagesEndRef = useRef<HTMLDivElement>(null);
  const synth = window.speechSynthesis;
  const [copiedMessageId, setCopiedMessageId] = useState<string | null>(null);

  // 语音识别钩子
  const { 
    transcript, 
    listening, 
    resetTranscript, 
    browserSupportsSpeechRecognition 
  } = useSpeechRecognition();

  // 检查浏览器是否支持语音识别
  useEffect(() => {
    if (!browserSupportsSpeechRecognition) {
      message.warning('您的浏览器不支持语音识别功能');
    }
  }, [browserSupportsSpeechRecognition]);

  // 滚动到最新消息
  useEffect(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  }, [messages]);

  // 处理语音输入
  useEffect(() => {
    if (listening && transcript) {
      setInputText(transcript);
    }
  }, [transcript, listening]);

  // 从文本中提取纯净的角色台词
  const extractPureMessage = (text: string): string => {
    // 使用Unicode转义序列表示标签字符，避免解析错误
    return text.replace(/\s*\n*\s*\uffe0\uffe1\uffe2[\s\S]*?\uffe0\uffe1\uffe2\s*\n*\s*/g, '').trim();
  };
  
  // 从响应数据中提取纯净文本
  const getMessageFromResponse = (data: any): string => {
    try {
      // 尝试解析JSON字符串格式的CharacterResponse
      if (typeof data === 'string') {
        try {
          const parsed = JSON.parse(data);
          if (parsed.message) {
            return parsed.message;
          }
        } catch (e) {
          // 如果不是有效的JSON，或者没有message字段，回退到处理原始文本
          return extractPureMessage(data);
        }
      }
      // 直接处理CharacterResponse对象
      if (typeof data === 'object' && data.message) {
        return data.message;
      }
      // 兜底情况
      return typeof data === 'string' ? extractPureMessage(data) : String(data);
    } catch (error) {
      console.error('提取消息文本失败:', error);
      return typeof data === 'string' ? data : String(data);
    }
  };
  
  // 处理文本到语音转换
  const speakMessage = (text: string) => {
    if (!isVoiceOutputActive) return;
    
    // 使用处理后的文本进行语音播报
    const cleanText = getMessageFromResponse(text);
    const utterance = new SpeechSynthesisUtterance(cleanText);
    utterance.lang = 'zh-CN'; // 默认使用中文
    utterance.volume = 1;
    utterance.rate = 1;
    utterance.pitch = 1;
    
    synth.speak(utterance);
  };



  // 从后端获取角色对话历史上下文
  const getConversationContext = (): string[] => {
    // 只取最近的5条消息作为上下文，避免上下文过长
    return messages.slice(-5).map(msg => msg.text);
  };

  // 发送消息
  const sendMessage = async () => {
    if (!inputText.trim()) return;

    const userMessage: Message = {
      id: `msg-${Date.now()}`,
      text: inputText.trim(),
      sender: 'user',
      timestamp: Date.now(),
      isVoice: false
    };

    setMessages(prevMessages => [...prevMessages, userMessage]);
    setInputText('');
    setIsTyping(true);

    try {
      // 从后端获取角色回复
      const context = getConversationContext();
      // 假设后端API会返回CharacterResponse格式的数据
      const response = await characterService.getCharacterResponse(
        character.id,
        inputText.trim(),
        context
      );
      
      // 处理可能的不同格式响应
      let characterMessage: Message;
      
      // 直接使用getMessageFromResponse函数提取纯净的消息文本
      const cleanMessage = getMessageFromResponse(response);
      
      // 创建角色消息，只使用干净的消息文本作为显示内容
      characterMessage = {
        id: `msg-${Date.now() + 1}`,
        text: cleanMessage,
        sender: 'character',
        timestamp: Date.now(),
        isVoice: true
      };

      setMessages(prevMessages => [...prevMessages, characterMessage]);
      speakMessage(cleanMessage);
    } catch (error) {
      console.error('获取角色回复失败:', error);
      message.error('获取角色回复失败，请稍后再试');
    } finally {
      setIsTyping(false);
    }
  };

  // 复制消息文本
  const copyMessageText = (messageId: string, text: string) => {
    // 复制处理后的消息文本
    const cleanText = getMessageFromResponse(text);
    navigator.clipboard.writeText(cleanText).then(() => {
      setCopiedMessageId(messageId);
      setTimeout(() => setCopiedMessageId(null), 2000);
    }).catch(() => {
      message.error('复制失败，请重试');
    });
  };

  // 切换语音输入
  const toggleVoiceInput = () => {
    if (listening) {
      SpeechRecognition.stopListening();
    } else {
      resetTranscript();
      SpeechRecognition.startListening({ continuous: true });
      setInputText('');
    }
  };

  // 切换语音输出
  const toggleVoiceOutput = () => {
    setIsVoiceOutputActive(!isVoiceOutputActive);
    if (synth.speaking) {
      synth.cancel();
    }
    message.info(isVoiceOutputActive ? '已关闭语音输出' : '已开启语音输出');
  };

  // 添加全局样式到document中
  useEffect(() => {
    // 检查是否已经添加了样式
    if (document.getElementById('conversation-panel-styles')) {
      return;
    }
    
    const style = document.createElement('style');
    style.id = 'conversation-panel-styles';
    style.textContent = `
      @keyframes fadeIn {
        from {
          opacity: 0;
          transform: translateY(10px);
        }
        to {
          opacity: 1;
          transform: translateY(0);
        }
      }
      
      @keyframes slideUp {
        from {
          opacity: 0;
          transform: translateY(10px);
        }
        to {
          opacity: 1;
          transform: translateY(0);
        }
      }
      
      @keyframes typing {
        0% { opacity: 0.3; }
        50% { opacity: 1; }
        100% { opacity: 0.3; }
      }
      
      .typing-animation {
        animation: typing 1.4s infinite;
      }
    `;
    
    document.head.appendChild(style);
    
    // 组件卸载时移除样式
    return () => {
      const element = document.getElementById('conversation-panel-styles');
      if (element) {
        element.remove();
      }
    };
  }, []);
  
  return (
    <div style={{ height: '100vh', display: 'flex', flexDirection: 'column', background: 'linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%)' }}>
      {/* 头部导航 */}
      <div style={{ 
        padding: '15px 20px', 
        backgroundColor: '#1890ff', 
        color: 'white', 
        display: 'flex', 
        alignItems: 'center', 
        justifyContent: 'space-between',
        boxShadow: '0 2px 8px rgba(0, 0, 0, 0.15)'
      }}>
        <div style={{ display: 'flex', alignItems: 'center' }}>
          <Button 
            type="text" 
            icon={<ArrowLeftOutlined />} 
            onClick={onBack} 
            style={{ color: 'white', padding: '4px 6px' }}
            size="small"
          />
          <Avatar 
            src={character.avatar} 
            alt={character.name} 
            style={{ marginLeft: '10px', width: 40, height: 40, border: '2px solid rgba(255, 255, 255, 0.3)' }}
          />
          <div style={{ marginLeft: '15px' }}>
            <h2 style={{ margin: 0 }}>{character.name}</h2>
            <p style={{ margin: '2px 0 0', opacity: 0.8, fontSize: '12px' }}>{character.description}</p>
          </div>
        </div>
        <Tooltip title={isVoiceOutputActive ? '关闭语音输出' : '开启语音输出'}>
          <Button 
            type="text" 
            icon={isVoiceOutputActive ? <SoundOutlined /> : <MutedOutlined />} 
            onClick={toggleVoiceOutput} 
            style={{ color: 'white' }}
            size="small"
          />
        </Tooltip>
      </div>

      {/* 对话内容区域 */}
      <div style={{ 
        flex: 1, 
        overflowY: 'auto', 
        padding: '20px',
        backgroundImage: `
          radial-gradient(circle at 25px 25px, #e8e8e8 2%, transparent 0%),
          radial-gradient(circle at 75px 75px, #e8e8e8 2%, transparent 0%)
        `,
        backgroundSize: '100px 100px'
      }}>
        {messages.length === 0 ? (
          <div style={{ 
            textAlign: 'center', 
            padding: '100px 20px', 
            color: '#8c8c8c' 
          }}>
            <MessageOutlined style={{ fontSize: '64px', marginBottom: '20px', opacity: 0.3 }} />
            <p>开始与{character.name}的对话吧！</p>
          </div>
        ) : (
          messages.map((message, index) => (
            <div key={message.id} style={{ marginBottom: '20px' }}>
              <div style={{
                display: 'flex',
                flexDirection: message.sender === 'user' ? 'row-reverse' : 'row',
                alignItems: 'flex-start',
                animation: 'fadeIn 0.3s ease-out'
              }}>
                <Avatar 
                  src={message.sender === 'user' ? undefined : character.avatar} 
                  icon={<UserOutlined />}
                  style={{
                    margin: message.sender === 'user' ? '0 0 0 10px' : '0 10px 0 0',
                    backgroundColor: message.sender === 'user' ? '#52c41a' : '#1890ff',
                    width: 36,
                    height: 36
                  }}
                />
                <div style={{
                  position: 'relative',
                  maxWidth: '70%',
                  backgroundColor: message.sender === 'user' ? '#52c41a' : '#ffffff',
                  color: message.sender === 'user' ? 'white' : '#333333',
                  padding: '12px 16px',
                  borderRadius: message.sender === 'user' ? '18px 8px 18px 18px' : '8px 18px 18px 18px',
                  boxShadow: '0 2px 10px rgba(0, 0, 0, 0.1)',
                  wordBreak: 'break-word',
                  transition: 'all 0.2s ease'
                }}>
                  {/* 聊天气泡的小三角 */}
                  <div style={{
                    position: 'absolute',
                    top: '10px',
                    width: 0,
                    height: 0,
                    borderStyle: 'solid',
                    borderWidth: '6px 10px 6px 0',
                    borderColor: `transparent ${message.sender === 'user' ? '#52c41a' : '#ffffff'} transparent transparent`,
                    transform: message.sender === 'user' ? 'translate(10px, 0)' : 'translate(-10px, 0)'
                  }}></div>
                  
                  <p style={{ margin: '0 0 6px 0', lineHeight: '1.5' }}>{getMessageFromResponse(message.text)}</p>
                  
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                    {message.isVoice && message.sender === 'character' && (
                      <span style={{ fontSize: '10px', opacity: 0.7, padding: '2px 6px', backgroundColor: 'rgba(255,255,255,0.2)', borderRadius: '4px' }}>
                        [语音回复]
                      </span>
                    )}
                    <span style={{ fontSize: '10px', opacity: 0.7 }}>
                      {formatTime(message.timestamp)}
                    </span>
                  </div>
                  
                  <Popconfirm
                    title="复制消息"
                    description="确定要复制这条消息吗？"
                    onConfirm={() => copyMessageText(message.id, message.text)}
                    okText="确定"
                    cancelText="取消"
                    placement="top"
                  >
                    <Button
                      type="text"
                      icon={copiedMessageId === message.id ? <CheckOutlined /> : <CopyOutlined />}
                      size="small"
                      style={{
                        position: 'absolute',
                        top: '4px',
                        right: '4px',
                        padding: '2px',
                        color: copiedMessageId === message.id ? '#52c41a' : (message.sender === 'user' ? 'rgba(255,255,255,0.7)' : 'rgba(0,0,0,0.3)'),
                        backgroundColor: 'transparent',
                        opacity: 0
                      }}
                      onMouseEnter={(e) => {
                        e.currentTarget.style.opacity = '1';
                      }}
                      onMouseLeave={(e) => {
                        if (copiedMessageId !== message.id) {
                          e.currentTarget.style.opacity = '0';
                        }
                      }}
                    />
                  </Popconfirm>
                </div>
              </div>
              
              {/* 显示"角色正在输入"的状态 */}
              {isTyping && index === messages.length - 1 && message.sender === 'user' && (
                <div style={{
                  marginLeft: '56px',
                  marginTop: '8px',
                  padding: '8px 12px',
                  backgroundColor: '#ffffff',
                  borderRadius: '12px',
                  display: 'flex',
                  alignItems: 'center',
                  boxShadow: '0 1px 4px rgba(0, 0, 0, 0.1)'
                }}>
                  <LoadingOutlined size={14} style={{ marginRight: '6px' }} />
                  <span style={{ fontSize: '12px', color: '#666' }}>{character.name} 正在输入...</span>
                </div>
              )}
            </div>
          ))
        )}
        <div ref={messagesEndRef} />
      </div>

      {/* 输入区域 */}
      <div style={{
        padding: '15px 20px', 
        backgroundColor: 'white', 
        borderTop: '1px solid #e8e8e8',
        boxShadow: '0 -2px 8px rgba(0, 0, 0, 0.05)',
        display: 'flex',
        alignItems: 'flex-end',
        gap: '10px'
      }}>
        <Tooltip title={listening ? "停止语音输入" : "语音输入"}>
          <Button
            type={listening ? 'primary' : 'default'}
            icon={listening ? <StopOutlined /> : <SoundOutlined />}
            onClick={toggleVoiceInput}
            disabled={!browserSupportsSpeechRecognition}
            style={{
              width: '40px',
              height: '40px',
              borderRadius: '50%',
              padding: 0,
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              transition: 'all 0.3s ease',
              backgroundColor: listening ? '#ff4d4f' : '#f0f0f0',
              border: 'none'
            }}
          />
        </Tooltip>
        
        <TextArea
          value={inputText}
          onChange={(e) => setInputText(e.target.value)}
          onPressEnter={() => sendMessage()}
          placeholder={`与${character.name}对话...`}
          autoSize={{ minRows: 2, maxRows: 4 }}
          style={{
            flex: 1,
            borderRadius: '18px',
            border: '1px solid #d9d9d9',
            transition: 'all 0.3s ease',
            boxShadow: 'inset 0 1px 3px rgba(0, 0, 0, 0.05)'
          }}
        />
        
        <Button
          type="primary"
          icon={<SendOutlined />}
          onClick={sendMessage}
          disabled={!inputText.trim()}
          style={{
            borderRadius: '20px',
            height: '40px',
            padding: '0 20px',
            transition: 'all 0.3s ease',
            border: 'none'
          }}
        >
          发送
        </Button>
      </div>
      
      {/* 正在聆听状态提示 */}
      {listening && (
        <div style={{
          margin: '0 20px 15px',
          padding: '10px 15px',
          backgroundColor: '#e6f7ff',
          borderRadius: '12px',
          fontSize: '14px',
          color: '#1890ff',
          border: '1px solid #91d5ff',
          boxShadow: '0 2px 4px rgba(0, 0, 0, 0.05)',
          transition: 'all 0.3s ease',
          animation: 'slideUp 0.3s ease-out'
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
            <SoundOutlined style={{ fontSize: '16px' }} className="typing-animation" />
            <span>正在聆听...</span>
            {transcript && (
              <span style={{ marginLeft: '10px', color: '#333', fontWeight: 500 }}>
                {transcript}
              </span>
            )}
          </div>
        </div>
      )}
    </div>
  );
};

export default ConversationPanel;